import { h, toRef, computed, resolveComponent } from 'vue'
import { useMessage } from 'naive-ui'
import { useApi, getHeaders } from '/@/api'
import { SIGN_URL } from '/@/config'

const UPLOAD_BTN_TEXT = '签名'
const UPLOAD_REMOVE_BTN_TEXT = '清除'

export const BookmarkItem = {
  props: ['name', 'modelValue', 'useUpload'],
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const modelValueRef = toRef(props, 'modelValue')
    const defaultFileList = []

    const Upload = resolveComponent('a-upload')
    const Space = resolveComponent('a-space')
    const Button = resolveComponent('a-button')
    const Image = resolveComponent('a-image')
    const Popconfirm = resolveComponent('a-popconfirm')

    const api = useApi()
    const message = useMessage()
    const remoteUrl = window.location.origin + '/api/tz/sign'

    function sign() {
      api.get('', {
        methodName: 'startSign',
        httpUrl: remoteUrl
      }, {
        retry: 0,
        timeout: false,
        prefixUrl: SIGN_URL
      })
        .then(res => {
          const { code, data } = res || {}

          if (code === 0) {
            emit('update:modelValue', data?.filepath)
          }
        })
        .catch(() => {
          message.error('调用签名设备失败，请检查')
        })
    }

    if (modelValueRef.value) {
      defaultFileList.push({
        uid: Date.now(),
        status: 'done',
        url: props.modelValue
      })
    }

    const useUpload = props.useUpload !== undefined &&
      props.useUpload !== false
    const upload = useUpload
      ? h(Upload, {
          action: '/api/upload',
          headers: getHeaders(),
          defaultFileList,
          showFileList: false,
          'onUpdate:fileList': files => {
            const [file] = files.slice(-1)

            if (file?.status === 'done') {
              const { code, data } = file?.response || {}

              if (code === 0) {
                emit('update:modelValue', data?.filepath)
              }
            }
          }
        }, {
          'upload-button': () => h(Button, {
            status: 'success',
            size: 'mini'
          }, { default: () => UPLOAD_BTN_TEXT })
        })
      :  h(Button, {
        status: 'success',
        size: 'mini',
        onClick: sign
      }, { default: () => UPLOAD_BTN_TEXT })

    const RightComp = h(Space, null, {
      default: () => {
        const comps = [upload]

        if (modelValueRef.value) {
          comps.unshift(
            h(Popconfirm, {
              content: '当前签名清除后无法恢复，请确定是否清除？',
              position: 'tr',
              onBeforeOk: done => {
                emit('update:modelValue', null),
                done()
              }
            }, {
              default: () => h(Button, {
                status: 'warning',
                size: 'mini',
              }, { default: () => UPLOAD_REMOVE_BTN_TEXT })
            })
          )
        }

        return comps
      }
    })

    const LeftCompRef = computed(() => {
      const comps = [h('span', {
        style: {
          marginRight: '8px'
        }
      }, props.name)]

      if (modelValueRef.value) {
        comps.push(
          h(Image, {
            height: 64,
            src: modelValueRef.value
          })
        )
      }

      return h('span', {
        style: { flex: 1 }
      }, comps)
    })

    return () => h('div', {
      class: 'bookmark-item',
      style: {
        display: 'flex'
      }
    }, [
      LeftCompRef.value,
      RightComp
    ])
  }
}
